import React, { Component } from 'react';
import { Tabs, Input, Select, Icon, Popconfirm, message } from 'antd';
import _ from 'lodash';
import cass from 'classnames';
import s from './index.module.less';
import { renderEmpty } from '../../common/commonRender';
import TitleItem from '../../../components/TitleItem';
import TreeSelect from '../../../components/TreeSelect';
import AutoComplete from '../../../components/AutoComplete';
import { EditInput, EditMultiInput, AntEditDatePicker } from '../../../components/EditComponent';
import LabelItem from '../../../components/LabelItem';
import ProjectRemark from './projectRemark';
import { canSaveStage } from './infoStageTab';
import { baseClient } from './infoStageAdd';

const Option = Select.Option;
const TabPane = Tabs.TabPane;
const configs = [
    { lable: '类型', key: 'rectype', require: true, options: [{ lable: '自然人', value: 1 }, { lable: '非自然人', value: 0 }] },
    { lable: '身份', key: 'title', require: true, options: [] },
    { lable: '姓名', lable0: '名称', key: 'name', require: true },
    { lable: '证件号码', lable0: '联系人', key: 'contact', require0: true },
    { lable: '联系电话', key: 'phone', require: true },
    { lable: '邮箱', key: 'mail' },
];

function stopEventDefault(e) {
    e.stopPropagation();
    e.preventDefault();
}

class InfoStageTabInfo extends Component {

    constructor(props) {
        super(props);
        this.state = {
            edit: false,
            stage: props.stage,
            defaultName: props.stage, // 保存用于取消操作
        }
    }

    // componentWillReceiveProps(nextProps){
    //     this.setState({ stage: nextProps.stage });
    // }

    // 不可修改，父组件要通过getValue()获取值
    getValue = () => {
        return this.state.stage;
    }

    renderItems(key, index, isClient) {
        const { edit, stage } = this.state;
        const { create, identities, detailData, col } = this.props;
        const { projecttype } = detailData;
        const target = stage.info[key][index];
        const isuserdefine = stage.isuserdefine;
        const { rectype, ...data } = target;
        let newConfigs = configs;
        if (projecttype === 3 || projecttype === 4) {
            newConfigs = [
                ...configs.slice(0, 1),
                ...configs.slice(2),
            ]
        }

        return newConfigs.map(v => {
            let value = data[v.key];
            let dom = (
                <Input
                    value={data[v.key]}
                    onChange={(e) => this.onClientItemsChange(key, { [v.key]: e.target.value }, index)}
                />
            );
            if (v.options && v.options.length) {
                value = rectype ? '自然人' : '非自然人';
                dom = (
                    <Select value={rectype} onChange={(e) => this.onClientItemsChange(key, { rectype: e }, index)}>
                        {v.options.map(o => <Option value={o.value} key={o.lable}>{o.lable}</Option>)}
                    </Select>
                )
            } else if (v.options && !v.options.length && !isuserdefine) {
                const { titleid, title } = target;
                value = title;
                dom = (
                    <Select
                        labelInValue
                        value={{ key: titleid, label: title }}
                        onChange={(e) => this.onClientItemsChange(key, { titleid: e.key, title: e.label }, index)}
                    >
                        {identities.map(o => <Option value={o.recid} key={o.recid}>{o.recname}</Option>)}
                    </Select>
                )
            }

            let labelText = v.lable;
            if (!rectype && v.lable0) labelText = v.lable0;

            let require = v.require && isClient;
            if (!rectype && v.require0) require = v.require0 && isClient;

            require = require && (edit || create);
            return (
                <LabelItem
                    key={v.lable}
                    col={col}
                    value={value}
                    label={labelText}
                    dom={dom}
                    require={require}
                    edit={edit || create}
                />
            )
        })
    }

    renderLitigant(canEdit) {
        const { stage } = this.state;
        const litigant = stage.info.litigant;
        return litigant.length ? (
            <Tabs>
                {litigant.map((v, i) => (
                    <TabPane
                        key={i}
                        tab={(
                            <div className={s.tabLable}>
                                {v.lable || `对方当事人${i + 1}`}
                                {
                                    canEdit ? (
                                        <Popconfirm
                                            title="确认删除该对方当事人？"
                                            okText="确定"
                                            cancelText="取消"
                                            placement="topRight"
                                            onConfirm={e => {
                                                stopEventDefault(e);
                                                this.deleteLitigant(i);
                                            }}
                                            onCancel={stopEventDefault}
                                        >
                                            <span
                                                className={cass('mdi mdi-close-circle', s.del)}
                                                onClick={stopEventDefault}
                                            />
                                        </Popconfirm>
                                    ) : null
                                }
                            </div>
                        )}
                    >
                        <div className={s.wrapEdit}>
                            {this.renderItems('litigant', i, false)}
                        </div>
                    </TabPane>
                ))}
            </Tabs>
        ) : renderEmpty('暂未添加对方当事人');
    }

    renderInfo(infoField, projecttype) {
        if (!infoField.length) return null;
        const { create, col } = this.props;
        const { edit, stage } = this.state;
        const data = stage.info;
        const stageid = stage.stageid;
        const doms = [];
        infoField.forEach((d, i) => {
            if (d.fieldname === 'client' || d.fieldname === 'litigant' || d.fieldname === 'remark') return;
            let value = data[d.fieldname];
            let node = (
                <EditInput
                    value={data[d.fieldname]}
                    edit={edit || create}
                    onChange={this.valueChange(d.fieldname)}
                    placeholder={`请输入${d.displayname}`}
                />
            );

            if (d.fieldname === 'causeofaction') {
                node = <TreeSelect value={value = data[d.fieldname]} projecttype={projecttype} onChange={this.valueChange(d.fieldname)} />
            } else if (d.fieldname === 'court') {
                node = <AutoComplete value={value = data[d.fieldname]} onChange={this.valueChange(d.fieldname)} />
            } else if (d.fieldname === 'fullcourt' || d.fieldname === 'clerk') {
                value = data[d.fieldname].map(v => v.name && v.phone ? `${v.name} | ${v.phone}` : '').join(', ') || '';
                node = <EditMultiInput value={data[d.fieldname]} edit={edit || create} onChange={this.valueChange(d.fieldname)} />
            } else if (d.fieldname === 'detentiondate' || d.fieldname === 'arrestdate') {
                node = (
                    <AntEditDatePicker
                        edit={edit || create}
                        value={data[d.fieldname]}
                        placeholder={`请选择${d.displayname}`}
                        onChange={this.valueChange(d.fieldname)}
                    />
                )
            }
            const dom = (
                <LabelItem
                    key={`${stageid}-${d.fieldname}-${i}`}
                    col={col}
                    label={d.displayname}
                    dom={node}
                    value={value}
                    edit={edit || create}
                />
            )

            doms.push(dom);
        });
        return doms;
    }

    addLitigant = () => {
        const { stage } = this.state;
        const info = JSON.parse(JSON.stringify(stage.info));
        const targetArr = info.litigant;
        targetArr.push({ ...baseClient });
        this.setState({ stage: { ...stage, info } });
    }

    deleteLitigant = (i) => {
        const { stage } = this.state;
        const info = JSON.parse(JSON.stringify(stage.info));
        const targetArr = info.litigant;
        const newArr = [
            ...targetArr.slice(0, i),
            ...targetArr.slice(i + 1),
        ];
        info.litigant = newArr;
        this.setState({ stage: { ...stage, info } });
    }

    // 保存info属性值的变更
    valueChange = (key) => (v) => {
        console.log('--valueChange--', key, v);
        const { stage } = this.state;
        const info = JSON.parse(JSON.stringify(stage.info));
        info[key] = v;
        this.setState({ stage: { ...stage, info } });
    }

    // 保存info.client, info.litigant属性值的变更
    onClientItemsChange = (objKey, newObj, index) => {
        // console.log('--onClientItemsChange--', objKey, newObj, index);
        const { stage } = this.state;
        const info = JSON.parse(JSON.stringify(stage.info));
        const target = info[objKey][index] || {};
        info[objKey][index] = { ...target, ...newObj };
        this.setState({ stage: { ...stage, info } });
    }

    getShareDataSource = () => {
        const { stage } = this.state;
        const shareDataSource = [
            ..._.get(stage, 'members', []) || [],
            ..._.get(stage, 'info.client[0].members', []) || []
        ];

        const dataSource = [];
        const obj = {}; // 去重处理
        shareDataSource.forEach(v => {
            if (!obj[v.userid] && (v.userid - 0) !== (window.localStorage.getItem('userId') - 0)) {
                dataSource.push(v);
                obj[v.userid] = v.userid;
            }
        })
        return dataSource;
    }

    // 取消编辑
    onCancel = () => {
        this.setState({
            stage: this.state.defaultName,
            edit: false
        })
    }

    onSave = () => {
        const { stage } = this.state;
        const {
            detailData: { projecttype, projectid },
            projectState: { saveInfo }
        } = this.props;
        const canSave = canSaveStage(stage, projecttype);
        if (!canSave) return;
        saveInfo({ projectid, stageid: stage.stageid, info: stage.info }, () => {
            message.success('修改成功');
            this.setState({ edit: false, defaultName: stage }); // 更新defaultName
        })
    }

    renderInfoEditBtn = () => {
        const { edit } = this.state;
        const { create, isLawyer, stage } = this.props;
        let infoEditBtn = null;
        if (!create && isLawyer && !stage.iscomplete && !stage.isNewStage) {
            infoEditBtn = (
                edit ?
                    [
                        <span onClick={this.onCancel} key="cancle" className={s.save}>取消</span>,
                        <span onClick={this.onSave} key="edit" className={s.save}>保存</span>,
                    ] :
                    <Icon type="edit" onClick={() => this.setState({ edit: true })} className="mainColor" />
            )
        }
        return infoEditBtn;
    }

    render() {

        const { edit, stage } = this.state;
        const { create, infoField, detailData, userState, col } = this.props;
        const { projecttype } = detailData;
        return (
            <>
                <TitleItem
                    title={'信息'}
                    icon={this.renderInfoEditBtn()}
                />
                <div className={s.wrapInfo}>
                    <div className={s.client}>委托人</div>
                    <div className={s.wrapEdit}>
                        {this.renderItems('client', 0, true)}
                    </div>
                    <div className={s.client}>
                        对方当事人
                        {(create || edit) ? <span className="mdi mdi-plus-box" onClick={this.addLitigant} /> : null}
                    </div>
                    {this.renderLitigant((create || edit))}
                </div>
                <div className={cass(s.wrapEdit, s.wrapEdit1)}>
                    {this.renderInfo(infoField, projecttype)}
                    <ProjectRemark
                        col={col}
                        edit={edit}
                        create={create}
                        info={userState.info}
                        data={stage}
                        onChange={this.valueChange('remarks')}
                        dataSource={this.getShareDataSource()}
                    />
                </div>
            </>
        );
    }
}

export default InfoStageTabInfo